package com.zw.yzk.kabu.adapter.header;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;


/**
 * Created by zhanwei on 2017/1/8.
 */

public class HeaderHelper {

    private WrapperAdapter wrapperAdapter;

    private HeaderHelper(RecyclerView.Adapter adapter) {
        if (adapter == null) {
            throw new RuntimeException("adapter could not be null");
        }
        wrapperAdapter = new WrapperAdapter(adapter);
        adapter.registerAdapterDataObserver(mDataObserver);
    }

    public static HeaderHelper createHelper(RecyclerView.Adapter adapter) {
        return new HeaderHelper(adapter);
    }

    /**
     * 添加header
     *
     * @param recyclerView 列表
     * @param view         header
     */
    public void addHeader(RecyclerView recyclerView, View view) {
        wrapperAdapter.setHeader(view);
        recyclerView.setAdapter(wrapperAdapter);
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            WrapperSpanSizeLookup wrapperSpanSizeLookup = new WrapperSpanSizeLookup(
                    ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanSizeLookup(),
                    (GridLayoutManager) recyclerView.getLayoutManager(),
                    wrapperAdapter);
            ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup(wrapperSpanSizeLookup);
        }
    }

    /**
     * 移除header
     */
    public void removeHeader() {
        wrapperAdapter.removeHeader();
    }

    private final RecyclerView.AdapterDataObserver mDataObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            wrapperAdapter.notifyDataSetChanged();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            wrapperAdapter.notifyItemRangeInserted(positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            wrapperAdapter.notifyItemRangeChanged(positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            wrapperAdapter.notifyItemRangeChanged(positionStart, itemCount, payload);
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            wrapperAdapter.notifyItemRangeRemoved(positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            wrapperAdapter.notifyItemMoved(fromPosition, toPosition);
        }
    };
}
